﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;

namespace Brc_PaaS.Dal
{
    public class Repository<T> : IRepository<T> where T : class, new()
    {
        private DbContext _context;
        public Repository(IConfiguration configuration)
        {
            _context = new DbContext(configuration);
        }

        public int AddItem(T model)
        {
            return _context.Instance.Insertable(model).ExecuteCommand();
        }
        public int AddList(List<T> list)
        {
            return _context.Instance.Insertable<T>(list).ExecuteCommand();
        }
        public int Delete(Expression<Func<T, bool>> WhereLambda)
        {
            return _context.Instance.Deleteable<T>(WhereLambda).ExecuteCommand();
        }

        public int Delete(dynamic[] ids)
        {
            return _context.Instance.Deleteable<T>(ids).ExecuteCommand();
        }

        public T Get(Expression<Func<T, bool>> WhereLambda)
        {
            return _context.Instance.Queryable<T>().First(WhereLambda);
        }

        public List<T> GetList(Expression<Func<T, bool>> WhereLambda)
        {
            return _context.Instance.Queryable<T>().Where(WhereLambda).ToList();
        }

        public List<T> GetPageList(Expression<Func<T, bool>> WhereLambda, int pageIndex, int pageSize, out int total)
        {
            total = DataCount(WhereLambda);
            return _context.Instance.Queryable<T>().Where(WhereLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        public int Update(T model)
        {
            return _context.Instance.Updateable<T>(model).ExecuteCommand();
        }

        public int Update(List<T> list)
        {
            return _context.Instance.Updateable(list).ExecuteCommand();
        }

        public bool Exist(Expression<Func<T, bool>> WhereLambda)
        {
            return _context.Instance.Queryable<T>().Any(WhereLambda);
        }
        private int DataCount(Expression<Func<T, bool>> WhereLambda)
        {
            return _context.Instance.Queryable<T>().ToList().Count;
        }
    }
}
